package cocurrent;

import org.junit.Test;

import java.io.IOException;
import java.util.concurrent.Phaser;

public class PhaserTest {
    /**
     * 分段栅栏的概念，   每个阶段达到栅栏个数 进入onAdvance中， 每满足一次条件 递增到下个阶段触发一次进入onAdvance中
     */
    MyPhaser myPhaser = new MyPhaser();

    @Test
    public void test() throws IOException {
        myPhaser.bulkRegister(5);
        for (int i = 0; i < 5; i++) {
            int finalI = i;
            Thread thread = new Thread(() -> {
                try {
                    myPhaser.arriveAndAwaitAdvance();

                    myPhaser.arriveAndAwaitAdvance();

                    if (finalI >= 3) {
                        myPhaser.arriveAndAwaitAdvance();
                    } else {
                        myPhaser.arriveAndDeregister();
                    }

                } catch (Exception e) {
                    e.printStackTrace();
                }

            });
            thread.start();
        }
        System.in.read();

    }


    class MyPhaser extends Phaser {
        @Override
        protected boolean onAdvance(int phase, int registeredParties) {
            switch (phase) {
                case 0:
                    System.out.println("第一阶段" + registeredParties);
                    return false;
                case 1:
                    System.out.println("第二阶段" + registeredParties);
                    return false;
                case 2:
                    System.out.println("第三阶段：" + registeredParties);
                    return true;
                default:
                    return true;
            }
        }
    }
}
